﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{ await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml"); }
    @{ await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml"); }
    @*<!-- 引入 xlsx 库<script src="https://cdn.bootcdn.net/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>-->*@
    <script src="/lib/xlsx/xlsx.full.min.js?v=@DateTime.Now.Ticks"></script>

    <link href="/css/JobNumReach.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>JobNumReach</title>
    <style type="text/css">
        /*报表样式*/
        html, body {
            background: url(../images/ProcessCapacity/bgwhite.png) no-repeat;
            background-size: cover;
            font-size: .16rem;
            color: #ffffff;
            position: relative;
            width: 100%;
            height: 100%;
            font-family: myFirstFont !important;
            color: black;
        }

        .rightTop {
            background-color: #f7fdff;
        }

        .dropbtn, button {
            background-color: #0aa9cd;
        }

        #query > button {
            background-color: #0aa9cd;
            border: 2px solid #0aa9cd;
        }

        .dropdown-content {
            background-color: #12bed0;
        }

        .Zebra {
            background-color: #e5ecff;
        }

        .ZebraNo {
            background-color: #e8f1f9;
        }

        .ZebraTo {
            background-color: #ffffff;
        }

        .warn {
            background-color: #ffcccc;
        }

        .note {
            color: red;
            font-size: 0.15rem;
            font-weight: bolder;
        }

        .jobnum:hover {
            background-color: #b3f1fe;
        }

        /*END*/

        .truncate {
            max-width: 1.2rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        /*明细模态*/
        .show_mode {
            border-radius: 0.1rem;
            position: absolute;
            z-index: 99;
            height: 10.6rem;
            width: 100%;
            /*text-align: center;*/
            background: #a2c2e2;
            display: none;
        }

        .show_mode > .contentdetail > div {
            color: black;
            height: 33.3%;
            width: 50%;
            float: left;
            border-block: solid #ffffff 1px;
        }

        .show_mode > .contentdetail > div > label {
            color: black;
        }

        .detail {
            color: black;
            background-color: #dfe4ee;
            height: 3rem;
            width: 100%;
        }

        .mode_close {
            float: right;
        }

        .mode_close:hover {
            background-color: #848690;
        }
        /*end*/
        #btn_export {
            height: 0.3rem;
            font-size: 0.16rem;
            margin-left: 2px;
            border-radius: 2px;
            background-color: #e9e9ed;
            border: 1px solid #8f8f9d;
        }

        #btn_export:hover {
            background-color: #dddddd;
        }
        #table, #table-sub {
            background-image: url('../images/loading.gif');
            background-size: 0.8rem 0.8rem;
            background-repeat: no-repeat;
            background-position: center;
        }
    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden; color: black;">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Data@Label.Datum</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="JobNumProdExport('jobnum_prod')">@Label.Report@Label.Export</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border">
                    <div class="title note">@Label.JobNumReachRateNote</div>
                    <div id="board" class="chart">
                        <div class="query">
                            <span class="exampleInputProject tle">@Label.Time:</span>
                            <input type="date" id="startdate" name="startdate" placeholder="@Label.Start@Label.Time" style="width:1.5rem">
                            <span class="exampleInputProject tle">@Label.To</span>
                            <input type="date" id="enddate" name="enddate" placeholder="@Label.Start@Label.End" style="width: 1.5rem; margin-right: 0.2rem;">
                            <span class="exampleInputProject tle">@Html.Raw(Label.JobNum + Label.Type):</span>
                            <select id="cmb_jobnumtype" placeholder="select JobNumType">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <span class="exampleInputProject tle">ProjCode:</span>
                            <select id="cmb_proj_code" placeholder="select ProjCode">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <span class="exampleInputProject tle">@Html.Raw(Label.Product):</span>
                            <select id="cmb_product_code" placeholder="select ProductCode">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <span class="exampleInputProject tle">@Html.Raw(Label.JobNum):</span>
                            <select id="cmb_jobnum" placeholder="select JobNum">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <button id="btn_query" class="btn btn-primary  btn-sm col-md-12" type="button" onclick="Getdata()">@Label.Query</button>
                        </div>
                        <div id="table-container">
                            <div id="table"></div>
                            <div id="table-sub"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="show_mode">
            <div style="width:100%; height:0.3rem;">
                <div class="mode_close" style="height:100%;margin-right:10px;line-height:0.3rem;"><label style="font-size:0.17rem;color:white;">关闭&times;</label></div>
            </div>
            <div class="contentdetail"></div>
        </div>
    </div>

    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        $(".show_mode").css("display", "none");
        $('.mode_close').click(function () {
            $(".show_mode").css("display", "none");
            $(".contentdetail").empty();
            $(".contentdetail div").remove();
        });
        //模板初始化配置
        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 })
                }
            });

            function numberToUpperCase(number) {
                var uppercaseMonths = [
                    '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'
                ];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 1);
            $('.header-title').html("@Html.Raw(Label.JobNum + Label.ReachRate + Label.Report)");
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear();
                var myMonth = myDate.getMonth() + 1;
                var myToday = myDate.getDate();
                var myDay = myDate.getDay();
                var myHour = myDate.getHours();
                var myMinute = myDate.getMinutes();
                var mySecond = myDate.getSeconds();
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime;

                nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);
            // 设置全屏
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    // 判断浏览器设备类型
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {       //兼容火狐
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {    //兼容谷歌
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {        //兼容IE
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit+Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });
            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                if (endDate < startDate) {
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                endDate.setDate(endDate.getDate() - 1);
                var maxStartDate = endDate.toISOString().split('T')[0];
                $('#startdate').attr('max', maxStartDate);
                if (startDate > endDate) {
                    $('#startdate').val($(this).val());
                }
            });
        });
        //选中自动查询
        $(document).on('change', '#cmb_jobnumtype,#cmb_proj_code,#cmb_product_code,#cmb_jobnum', function () {
            $(".show_mode").css("display", "none");
            Getdata();
        });
        //json toXlsx
        function exportXlsx(data,name) {
            const book = XLSX.utils.book_new();
            const sheet = XLSX.utils.json_to_sheet(data);
            XLSX.utils.book_append_sheet(book, sheet);
            XLSX.writeFile(book, `${name}.xlsx`);
        }
        //exportXlsx(test_data,'Export');

        //定时查询
        var Tabtimer;
        function TabInterval() {
            clearInterval(Tabtimer);
            //每隔10m执行一次
            Tabtimer = setInterval(function () {
                var endDate = new Date($("#enddate").val());
                if (endDate > new Date()) {
                    getdate();
                }
            }, 10 * 60 * 1000);
        }

        var ComboxAction = function () {
            var jobnumtype = $("#cmb_jobnumtype");
            var projectsele = $("#cmb_proj_code");
            var productcode = $("#cmb_product_code");
            var jobnum = $("#cmb_jobnum");
            var pam = {};
            var header_key = {
                start_time: $('#startdate').val(),
                end_time: $('#enddate').val()
            };
            pam.header_key = JSON.stringify(header_key);
            loadData(jobnumtype, api + '/Assembly/GetJobNumType', false);
            jobnumtype.change(function () {
                header_key.jobnumtype = $(this).val();
                pam.header_key = JSON.stringify(header_key);
                loadData(projectsele, api + '/Assembly/GetJobNumProjCode', false);
            });
            projectsele.change(function () {
                pam.proj_code = $(this).val();
                header_key.jobnumtype = $("#cmb_jobnumtype").val();
                pam.header_key = JSON.stringify(header_key);
                loadData(productcode, api + '/Assembly/GetJobNumProductCode', false);
            });
            productcode.change(function () {
                pam.proj_code = $("#cmb_proj_code").val();
                pam.product_code = $(this).val();
                loadData(jobnum, api + '/Assembly/GetJobNum', false);
            });
            function loadData(selectElement, url, boolean) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: pam,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        selectdata = data.ReturnData;
                        selectElement.empty();
                        if (selectdata.length <= 0) {
                            var option = "<option>@Html.Raw(Label.No+Label.Correlation+Label.Data)</option>";
                            selectElement.append(option);
                            return;
                        }
                        if (boolean) {
                            selectElement.append("<option value=''>@Html.Raw(Label.PleaseSelect)...</option>");
                        } else {
                            selectElement.append("<option value='ALL'>@Html.Raw(Label.ALL)</option>");
                        }
                        $.each(selectdata, function (key, value) {
                            selectElement.append($('<option>', {
                                value: value.value,
                                text: value.text
                            }));
                        });
                    }
                });
            }
        }

        $(function () {
            var startDate = new Date();
            startDate.setMonth(startDate.getMonth() - 2);
            var endDate = new Date();
            endDate.setDate(endDate.getDate() + 1);
            $('#startdate').val(startDate.toISOString().split('T')[0]);
            $('#enddate').val(endDate.toISOString().split('T')[0]);
            ComboxAction();
            setTimeout(function () {
                $('#cmb_proj_code').prop('selectedIndex', 0);
                $('#cmb_product_code').prop('selectedIndex', 0);
                $('#cmb_month').prop('selectedIndex', 1);
                Getdata();
            }, 500);
        })

        var Getdata = function () {
            getdate();
            TabInterval();
        }

        /*导出生产数据*/
        var TestDataExport = function (type) {
            ExportType = type;
            var formData = new FormData();
            formData.append('type', ExportType);
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('process_id', $('#cmb_process_code').val() == null ? "ALL" : $('#cmb_process_code').val());
            formData.append('start_time', $("#startdate").val());
            formData.append('end_time', $("#enddate").val());
            var url = api + "/Dashboard/TestDataToExcel";
            PostExportToExcel(url, formData);
        }
        //报表导出
        var JobNumProdExport = function (type) {
            exportXlsx(Tab, type);
            /*
            var formData = new FormData();
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('product_code', $("#cmb_product_code").val());
            ExportType = type;
            var url = api + "/ReportAction/ErpWipReportToExcel";
            PostExportToExcel(url, formData);
            */
        }
        //POST 参数不固定 导出
        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }
        //导出
        var ExportToExcel = function (url) {
            //var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            /*
            GET:param
            var formData = new FormData();
            formData.append('CL_TYPE', $("#cmb_classtype").val());
            xhr.send(formData);
            */
            xhr.send();
        }
        //合并相同行
        function mergeFunc(tableId) {
            var tab = document.getElementById(tableId);
            var maxCol = 3;//maxcol用于设置需要合并的列数
            var count, start;
            for (var col = maxCol - 1; col >= 0; col--) {
                //用于存储相同个数
                count = 1;
                for (var i = 0; i < tab.rows.length; i++) {
                    if (i > 0 && col > 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML
                        && tab.rows[i].cells[col - 1].innerHTML == tab.rows[i - 1].cells[col - 1].innerHTML) {
                        count++;
                    } else if (i > 0 && col == 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML) {
                        count++;
                    } else {
                        if (count > 1) {
                            //合并
                            start = i - count;
                            tab.rows[start].cells[col].rowSpan = count;
                            for (var j = start + 1; j < i; j++) { //
                                tab.rows[j].removeChild(tab.rows[j].cells[col]);
                            }
                            count = 1;
                        }
                    }
                }
                if (count > 1) { //合并，最后几行相同的情况下
                    start = i - count;
                    tab.rows[start].cells[col].rowSpan = count;
                    for (var j = start + 1; j < i; j++) {
                        tab.rows[j].removeChild(tab.rows[j].cells[col]);
                    }
                }
            }
        }

        function loadingshow() {
            $('#table,#table-sub').css('background-image', 'url("../images/loading.gif")');
            $('#table,#table-sub').css('background-size', '0.8rem 0.8rem');
            $('#table,#table-sub').css('background-repeat', 'no-repeat');
            $('#table,#table-sub').css('background-position', 'center');
        }
        function loadingnone() {
            $('#table,#table-sub').css('background-image', 'none');
        }

        //获取数据
        var Tab;
        var getdate = function () {
            $('#btn_query').prop('disabled', true);
            $("#myTable>thead>tr, #yield_tbody,#myTable>tfoot>tr").empty();
            var header_key = {
                start_time: $('#startdate').val(),
                end_time: $('#enddate').val(),
                jobnumtype: $('#cmb_jobnumtype').val(),
                jobnum: $("#cmb_jobnum").val()
            };
            var pam = {};
            pam.proj_code = $('#cmb_proj_code').val();
            pam.product_code = $('#cmb_product_code').val();
            pam.header_key = JSON.stringify(header_key);
            if (pam.proj_code !== "-1") {
                loadingshow();
                $.ajax({
                    type: "POST",
                    url: api + "/Assembly/GetJobNumProductCodeReachRate",
                    data: pam,
                    dataType: "json",
                    async: true,
                    success: function (dt) {
                        loadingnone();
                        $('#btn_query').prop('disabled', false);
                        Tab = dt.ReturnData;
                        prod_finish_boarddata()
                    }
                });
            }
        }
        //dataZoom 自动滚动
        var Zoom = function (id, myChart, option,data) {
            var autoScrollTimer;
            var scrollSpeed = 1;
            $(`#${id}`).mouseleave(function () {
                clearInterval(autoScrollTimer);
                autoScrollTimer = setInterval(function () {
                    var dataZoom = option.dataZoom[0];
                    var newStart = dataZoom.start + scrollSpeed;
                    var newEnd = dataZoom.end + scrollSpeed;
                    if (newEnd >= 100) {
                        newStart = 0;
                        newEnd = parseInt(30 / data.length * 100);
                    }
                    dataZoom.start = newStart;
                    dataZoom.end = newEnd;
                    myChart.setOption({
                        dataZoom: option.dataZoom
                    });
                }, 3000);
            });
            $(`#${id}`).mouseenter(function () {
                clearInterval(autoScrollTimer);
            });
        }
        //工段达标率报表
        var prod_finish_boarddata = function () {
            $('#btn_query').prop('disabled', false);
            var data = Tab;
            $("#table").empty();
            var tester_end_html = `
            <table id="myTable" class="DataSheet" border="1" style="width: 100%; height: 100%;">
                <thead><tr></tr></thead>
                <tbody id="yield_tbody"></tbody>
                <tfoot><tr></tr></tfoot>
            </table>`;
            $("#table").append(tester_end_html);
            var table = $('#myTable');
            var tbody = table.find('tbody');
            $("#myTable>thead>tr, #yield_tbody,#myTable>tfoot>tr").empty();
            // 动态生成表头
            var headerRow = table.find('thead tr');
            var headers = Object.keys(data[0]);
            headers.forEach(function (header) {
                headerRow.append('<th>' + header + '</th>');
            });
            // 生成表格内容
            data.forEach(function (row, index) {
                index++;
                var newRow = $(`<tr class="${(index % 2) > 0 ? "ZebraNo" : "ZebraTo"}"></tr>`);
                headers.forEach(function (header, columnindex) {
                    if (typeof row[header] === "number") {
                        if (header === "YIELD" || header === "FINISH_RATE") {
                            row[header] = parseFloat(row[header]).toFixed(2) + '%';
                        } else {
                            row[header] = row[header].toFixed(0);
                        }
                    }
                    if (header === "CREATE_TIME") {
                        row[header] = row[header].replace(/\T/g, '&emsp;');
                    }

                    if (header === "JOB_NUM") {
                        newRow.append(`<td class="truncate jobnum" onclick="process_finish_data('${row["ID"]}','${row[header]}');"><a style="color:blue;font-weight:bolder;">${row[header]}</a></td>`);
                    }
                    else {
                        if ((header === "YIELD" || header === "FINISH_RATE") && parseInt(row[header].replace(/\%/g, '')) <= 90) {
                            newRow.append(`<td class="truncate warn">${row[header]}</td>`);
                        } else {
                            newRow.append(`<td class="truncate">${row[header]}</td>`);
                        }
                    }
                });
                tbody.append(newRow);
            });
            // 合计
            var colspan = 5;
            var tfootRow = table.find('tfoot tr');
            tfootRow.append(`<th colspan="${colspan}">合计</th>`);
            var sum_input = data.reduce(function (sum, item) {
                return sum + (item ? (parseFloat(item.INPUT) || 0) : 0);
            }, 0);
            var sum_output = data.reduce(function (sum, item) {
                return sum + (item ? (parseFloat(item.OUTPUT) || 0) : 0);
            }, 0);
            headers.forEach(function (header, columnindex) {
                if (columnindex >= colspan) {
                    var sum = 0;
                    data.forEach(function (row, index) {
                        sum = parseInt(row[header]) + sum;
                    });
                    //总的良率
                    if (header === "YIELD") {
                        sum = parseFloat(sum_input > 0 ? (sum_output / sum_input) * 100 : 0).toFixed(2) + '%';
                    }
                    if (header === "FINISH_RATE" || header === "CREATE_TIME") {
                        sum = "";
                    }
                    tfootRow.append(`<th>${sum}</th>`);
                }
            });
            /*mergeFunc("myTable");//合并*/
            $("#table-sub").empty();
            var charthtml = `
            <div style="width:100%;height:50%;">
                <div id="finishchart" class="detail" style="height: 4.65rem; background-color: white;"></div>
            </div>
            <div style="width:100%;height:50%;">
                <div id="yieldchart" class="detail" style="height: 4.65rem; background-color: white;"></div>
            </div>`;
            $("#table-sub").append(charthtml);
            jobnum_finish_Chart();
            jobnum_yield_Chart();

        }
        //工段达标率chart
        var jobnum_finish_Chart = function () {
            var chartDom = document.getElementById("finishchart");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            var myChart = echarts.init(chartDom);
            var xAxisData = Tab.map(function (item) {
                return item ? item.JOB_NUM : 0;
            });
            var pass = Tab.map(function (item) {
                return item ? item.OUTPUT : 0;
            });
            var fail = Tab.map(function (item) {
                return item ? item.INPUT - item.OUTPUT : 0;
            });
            var finish = Tab.map(function (item) {
                return parseInt(item.FINISH_RATE.replace(/\%/g, ''));
            });
            var InputData = Tab.map(function (item) {
                return item ? item.INPUT : 0;
            });
            var vaulemax = Math.max.apply(null, InputData);
            var yAxismax = Math.ceil(vaulemax) + (10 - Math.ceil(vaulemax) % 10);
            var options = {
                label: {
                    show: true,
                    color: 'white',
                    fontSize: '0.1rem',
                    fontWeight: 'bold'
                },
                title: {
                    text: "工段达标率FINISH",
                    textStyle: {
                        fontSize: '0.14rem',
                        textAlign: 'center'
                    }
                },
                textStyle: {
                    fontSize: '0.1rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.12rem',
                        align: 'left'
                    },
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    data: ['PASS', 'FAIL', 'FINISH'],
                    width: '100%',
                    itemGap: 10,
                    itemWidth: 10,
                    itemHeight: 10,
                    textStyle: {
                        fontSize: '0.14rem'
                    }
                },
                grid: {
                    left: '2%',
                    right: '2%',
                    bottom: '12%',
                    containLabel: true
                },
                xAxis:
                {
                    yAxisIndex: 9,
                    type: 'category',
                    data: xAxisData,
                    textStyle: {
                        fontSize: '0.12rem'
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: 45,
                        textStyle: {
                            fontSize: '0.10rem'
                        }
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        max: yAxismax + (yAxismax / 5),
                        interval: Math.ceil((yAxismax + (yAxismax / 5)) / 6),
                        splitLine: { show: false },
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            interval: 0,
                            textStyle: {
                                fontSize: '0.10rem',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    {
                        type: 'value',
                        min: 0,
                        max: 120,
                        interval: 20,
                        scale: true,//刻度范围一致
                        splitLine: { show: false },
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            interval: 0,
                            formatter: function (value) {
                                return value + '%';
                            },
                            textStyle: {
                                fontSize: '0.10rem',
                                fontWeight: 'bold'
                            }
                        }
                    }
                ],
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: parseInt(30 / Tab.length * 100),
                        xAxisIndex: [0, 1],
                        zoomOnMouseWheel: false
                    },
                    {
                        type: 'slider',
                        start: 0,
                        end: parseInt(30 / Tab.length) * 100,
                        xAxisIndex: [0, 1],
                        handleSize: 0,
                        zoomLock: true
                    }
                ],
                series: [
                    {
                        data: fail.map(item => parseInt(item) > 0 ? item : null),
                        name: 'FAIL',
                        type: 'bar',
                        stack: 'stack1',
                        zlevel: 1,
                        barCategoryGap: '50%',
                        barWidth: '40%',
                        itemStyle: {
                            normal: {
                                color: '#FF3374',
                                shadowColor: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    {
                        data: pass.map(item => parseInt(item) > 0 ? item : null),
                        name: 'PASS',
                        type: 'bar',
                        stack: 'stack1',
                        zlevel: 1,
                        barCategoryGap: '50%',
                        barWidth: '40%',
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: '#07C160',
                                shadowColor: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    {
                        name: 'FINISH',
                        type: 'line',
                        yAxisIndex: 1,
                        zlevel: 0,
                        data: finish.map(item => parseInt(item) > 0 ? item : 0),
                        lineStyle: { normal: { width: 3 } },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                    offset: 0,
                                    color: 'rgba(3, 194, 236, 0.5)'
                                }, {
                                    offset: 0.8,
                                    color: 'rgba(3, 194, 236, 0.1)'
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                                shadowBlur: 10
                            }
                        },
                        itemStyle: { normal: { color: '#03C2EC' } },
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                formatter: function (params) { return params.value + '%'; },
                                color: '#03BFE9'
                            }
                        }
                    }
                ]
            };
            myChart.setOption(options);
            //dataZoom 自动滚动
            Zoom("finishchart", myChart, options, Tab);
            myChart.on('click', function (params) {
                var row = Tab.filter(function (item) {
                    return item.JOB_NUM == params.name;
                });
                process_finish_data(row[0].ID, params.name)
                //jobnum_day_prod();
            });
            window.addEventListener('resize', function () {
                myChart.resize();
            });

        }
        //工段良率chart
        var jobnum_yield_Chart = function () {
            var chartDom = document.getElementById("yieldchart");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            var myChart = echarts.init(chartDom);
            var xAxisData = Tab.map(function (item) {
                return item ? item.JOB_NUM : 0;
            });
            var pass = Tab.map(function (item) {
                return item ? item.OUTPUT : 0;
            });
            var fail = Tab.map(function (item) {
                return item ? item.INPUT - item.OUTPUT : 0;
            });
            var yield = Tab.map(function (item) {
                return parseInt(item.YIELD.replace(/\%/g, ''));
            });
            var InputData = Tab.map(function (item) {
                return item ? item.INPUT : 0;
            });
            var vaulemax = Math.max.apply(null, InputData);
            var yAxismax = Math.ceil(vaulemax) + (10 - Math.ceil(vaulemax) % 10);
            var options = {
                label: {
                    show: true,
                    color: 'white',
                    fontSize: '0.1rem',
                    fontWeight: 'bold'
                },
                title: {
                    text: "工段良率YIELD",
                    textStyle: {
                        fontSize: '0.14rem',
                        textAlign: 'center'
                    }
                },
                textStyle: {
                    fontSize: '0.1rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.12rem',
                        align: 'left'
                    },
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    data: ['PASS', 'FAIL', 'YIELD'],
                    width: '100%',
                    itemGap: 10,
                    itemWidth: 10,
                    itemHeight: 10,
                    textStyle: {
                        fontSize: '0.14rem'
                    }
                },
                grid: {
                    left: '2%',
                    right: '2%',
                    bottom: '12%',
                    containLabel: true
                },
                xAxis:
                {
                    yAxisIndex: 9,
                    type: 'category',
                    data: xAxisData,
                    textStyle: {
                        fontSize: '0.12rem'
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: 45,
                        textStyle: {
                            fontSize: '0.10rem'
                        }
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        max: yAxismax + (yAxismax / 5),
                        interval: Math.ceil((yAxismax + (yAxismax / 5)) / 6),
                        splitLine: { show: false },
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            interval: 0,
                            textStyle: {
                                fontSize: '0.10rem',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    {
                        type: 'value',
                        min: 0,
                        max: 120,
                        interval: 20,
                        scale: true,//刻度范围一致
                        splitLine: { show: false },
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            interval: 0,
                            formatter: function (value) {
                                return value + '%';
                            },
                            textStyle: {
                                fontSize: '0.10rem',
                                fontWeight: 'bold'
                            }
                        }
                    }
                ],
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: parseInt(30 / Tab.length * 100),
                        xAxisIndex: [0, 1],
                        zoomOnMouseWheel: false
                    },
                    {
                        type: 'slider',
                        start: 0,
                        end: parseInt(30 / Tab.length) * 100,
                        xAxisIndex: [0, 1],
                        handleSize: 0,
                        zoomLock: true
                    }
                ],
                series: [
                    {
                        data: fail.map(item => parseInt(item) > 0 ? item : null),
                        name: 'FAIL',
                        type: 'bar',
                        stack: 'stack1',
                        zlevel: 1,
                        barCategoryGap: '50%',
                        barWidth: '40%',
                        itemStyle: {
                            normal: {
                                color: '#FF3374',
                                shadowColor: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    {
                        data: pass.map(item => parseInt(item) > 0 ? item : null),
                        name: 'PASS',
                        type: 'bar',
                        stack: 'stack1',
                        zlevel: 1,
                        barCategoryGap: '50%',
                        barWidth: '40%',
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: '#07C160',
                                shadowColor: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    {
                        name: 'YIELD',
                        type: 'line',
                        yAxisIndex: 1,
                        zlevel: 0,
                        data: yield.map(item => parseInt(item) > 0 ? item : 0),
                        lineStyle: { normal: { width: 3 } },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                    offset: 0,
                                    color: 'rgba(237, 178, 23, 0.5)'
                                }, {
                                    offset: 0.8,
                                    color: 'rgba(237, 178, 23, 0.1)'
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                                shadowBlur: 10
                            }
                        },
                        itemStyle: { normal: { color: '#EDB217 ' } },
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                formatter: function (params) { return params.value + '%'; },
                                color: '#E1AB19'
                            }
                        }
                    }
                ]
            };
            myChart.setOption(options);
            //dataZoom 自动滚动
            Zoom("yieldchart", myChart, options, Tab);
            myChart.on('click', function (params) {
                var row = Tab.filter(function (item) {
                    return item.JOB_NUM == params.name;
                });
                process_finish_data(row[0].ID, params.name)
                //jobnum_day_prod();
            });
            window.addEventListener('resize', function () {
                myChart.resize();
            });
        }

        //工序达标率data
        var ProdTab = {};
        var ProcessTab;
        var process_finish_data = function (id,job_num) {
            var header_key = {
                jobnum: job_num
            };
            var pam = {};
            pam.header_key = JSON.stringify(header_key);
            $.ajax({
                type: "POST",
                url: api + "/Assembly/GetJobNumProcessReachRate",
                data: pam,
                dataType: "json",
                async: false,
                success: function (dt) {
                    $('#btn_query').prop('disabled', false);
                    ProdTab.Tab1 = dt.ReturnData.Table; //工序达标率
                    ProdTab.Tab2 = dt.ReturnData.Table1;//数据明细
                    ProdTab.Tab3 = dt.ReturnData.Table2;//工单&工序by每天小时产出
                    ProdTab.Tab4 = dt.ReturnData.Table3;//工单by每天小时产出
                    ProcessTab = ProdTab.Tab1;
                    process_finish_boarddata();
                    process_finish_Chart(id,job_num);
                }
            });
        }
        //工序达标率 列表
        var process_finish_boarddata = function () {
            $("#yieldchart").empty();
            var charthtml = `
            <table id="ProcessTable" class="DataSheet" border="1" style="width: 100%; height: 100%;">
                <thead><tr></tr></thead>
                <tbody id="p_finish_tbody"></tbody>
                <tfoot><tr></tr></tfoot>
            </table>`;
            $("#yieldchart").append(charthtml);
            $("#yieldchart").css("overflow-y", "auto");
            $('#btn_query').prop('disabled', false);
            var data = ProcessTab;
            var table = $('#ProcessTable');
            var tbody = table.find('tbody');
            $("#ProcessTable>thead>tr,#p_finish_tbody,#ProcessTable>tfoot>tr").empty();
            // 动态生成表头
            var headerRow = table.find('thead tr');
            var headers = Object.keys(data[0]);
            headers.forEach(function (header) {
                headerRow.append('<th>' + header + '</th>');
            });
            // 生成表格内容
            data.forEach(function (row, index) {
                index++;
                var newRow = $(`<tr class="${(index % 2) > 0 ? "Zebra" : "ZebraTo"}"></tr>`);
                headers.forEach(function (header, columnindex) {
                    if (typeof row[header] === "number") {
                        if (header === "YIELD" || header === "FINISH_RATE") {
                            row[header] = parseFloat(row[header]).toFixed(2) + '%';
                        } else {
                            row[header] = row[header].toFixed(0);
                        }
                    }
                    if (header === "CREATE_TIME") {
                        row[header] = row[header].replace(/\T/g, '&emsp;');
                    }
                    if ((header === "YIELD" || header === "FINISH_RATE") && parseInt(row[header].replace(/\%/g, '')) <= 90) {
                        newRow.append(`<td class="truncate warn">${row[header]}</td>`);
                    }
                    else {
                        if (header === "JOB_NUM") {
                            newRow.append(`<td class="truncate jobnum" onclick="jobnum_day_prod();"><a style="color:blue;font-weight:bolder;">${row[header]}</a></td>`);
                        }
                        else {
                            newRow.append(`<td class="truncate">${row[header]}</td>`);
                        }
                    }
                });
                tbody.append(newRow);
            });
            // 合计
            var colspan = 6;
            var tfootRow = table.find('tfoot tr');
            tfootRow.append(`<th colspan="${colspan}">合计</th>`);
            var sum_req_qty = data.reduce(function (sum, item) {
                return sum + (item ? (parseFloat(item.REQ_QTY) || 0) : 0);
            }, 0);
            var sum_input = data.reduce(function (sum, item) {
                return sum + (item ? (parseFloat(item.INPUT) || 0) : 0);
            }, 0);
            var sum_output = data.reduce(function (sum, item) {
                return sum + (item ? (parseFloat(item.OUTPUT) || 0) : 0);
            }, 0);
            var fpyrate = data.reduce(function (yield, item) {
                return yield * (item ? (parseFloat(item.YIELD.replace('%', '')) / 100 || 0) : 0);
            }, 1);
            headers.forEach(function (header, columnindex) {
                if (columnindex >= colspan) {
                    var sum = 0;
                    data.forEach(function (row, index) {
                        sum = parseInt(row[header]) + sum;
                    });
                    //直通率
                    if (header === "YIELD") {
                        //sum = parseFloat(sum_input > 0 ? (sum_output / sum_input) * 100 : 0).toFixed(2) + '%';//总的良率
                        sum = (fpyrate * 100).toFixed(2) + '%';
                    }
                    //总的FINISH_RATE
                    if (header === "FINISH_RATE") {
                        sum = parseFloat(sum_input > 0 ? (sum_output / sum_req_qty) * 100 : 0).toFixed(2) + '%';
                    }
                    if (header === "CREATE_TIME") {
                        sum = "";
                    }
                    tfootRow.append(`<th>${sum}</th>`);
                }
            });
        }
        //工序达标率Chart
        var process_finish_Chart = function (id,job_num) {
            var chartDom = document.getElementById("finishchart");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            var myChart = echarts.init(chartDom);
            var xAxisData = ProcessTab.map(function (item) {
                return item.PROCESS_ID;
            });
            var pass = ProcessTab.map(function (item) {
                return item ? item.OUTPUT : 0;
            });
            var fail = ProcessTab.map(function (item) {
                return item ? item.INPUT - item.OUTPUT : 0;
            });
            var finish = ProcessTab.map(function (item) {
                return parseInt(item.FINISH_RATE.replace(/\%/g, ''));
            });
            var yield = ProcessTab.map(function (item) {
                return parseInt(item.YIELD.replace(/\%/g, ''));
            });
            var InputData = ProcessTab.map(function (item) {
                return item ? item.INPUT : 0;
            });
            var vaulemax = Math.max.apply(null, InputData);
            var yAxismax = Math.ceil(vaulemax) + (10 - Math.ceil(vaulemax) % 10);
            var options = {
                label: {
                    show: true,
                    color: 'white',
                    fontSize: '0.1rem',
                    fontWeight: 'bold'
                },
                title: {
                    text: `${id}:${job_num}`,
                    textStyle: {
                        fontSize: '0.14rem',
                        textAlign: 'center'
                    }
                },
                textStyle: {
                    fontSize: '0.1rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.12rem',
                        align: 'left'
                    },
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    data: ['PASS', 'FAIL', 'FINISH'],
                    width: '100%',
                    itemGap: 10,
                    itemWidth: 10,
                    itemHeight: 10,
                    textStyle: {
                        fontSize: '0.14rem'
                    }
                },
                grid: {
                    left: '2%',
                    right: '2%',
                    bottom: '12%',
                    containLabel: true
                },
                xAxis:
                {
                    yAxisIndex: 9,
                    type: 'category',
                    data: xAxisData,
                    textStyle: {
                        fontSize: '0.12rem'
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: 45,
                        textStyle: {
                            fontSize: '0.10rem'
                        }
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        max: yAxismax * 2 + (yAxismax / 5),
                        interval: Math.ceil((yAxismax *2 + (yAxismax / 5)) / 6),
                        splitLine: { show: false },
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            interval: 0,
                            textStyle: {
                                fontSize: '0.10rem',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    {
                        type: 'value',
                        min: 0,
                        max: 120,
                        interval: 20,
                        scale: true,//刻度范围一致
                        splitLine: { show: false },
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            interval: 0,
                            formatter: function (value) {
                                return value + '%';
                            },
                            textStyle: {
                                fontSize: '0.10rem',
                                fontWeight: 'bold'
                            }
                        }
                    }
                ],
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: parseInt(30 / ProcessTab.length * 100),
                        xAxisIndex: [0, 1],
                        zoomOnMouseWheel: false
                    },
                    {
                        type: 'slider',
                        start: 0,
                        end: parseInt(30 / ProcessTab.length) * 100,
                        xAxisIndex: [0, 1],
                        handleSize: 0,
                        zoomLock: true
                    }
                ],
                series: [
                    {
                        data: fail.map(item => parseInt(item) > 0 ? item : null),
                        name: 'FAIL',
                        type: 'bar',
                        stack: 'stack1',
                        zlevel: 1,
                        barCategoryGap: '50%',
                        barWidth: '40%',
                        itemStyle: {
                            normal: {
                                color: '#FF3374',
                                shadowColor: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    {
                        data: pass.map(item => parseInt(item) > 0 ? item : null),
                        name: 'PASS',
                        type: 'bar',
                        stack: 'stack1',
                        zlevel: 1,
                        barCategoryGap: '50%',
                        barWidth: '40%',
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: '#07C160',
                                shadowColor: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    {
                        name: 'FINISH',
                        type: 'line',
                        yAxisIndex: 1,
                        zlevel: 0,
                        data: finish.map(item => parseInt(item) > 0 ? item : 0),
                        lineStyle: { normal: { width: 3 } },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                    offset: 0,
                                    color: 'rgba(3, 194, 236, 0.5)'
                                }, {
                                    offset: 0.8,
                                    color: 'rgba(3, 194, 236, 0.1)'
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                                shadowBlur: 10
                            }
                        },
                        itemStyle: { normal: { color: '#03C2EC' } },
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                formatter: function (params) { return params.value + '%'; },
                                color: '#03BFE9'
                            }
                        }
                    }
                ]
            };
            myChart.setOption(options);
            myChart.on('click', function (params) {
                jobnum_day_prod();
            });
            window.addEventListener('resize', function () {
                myChart.resize();
            });
        }

        /*数据下钻*/
        var jobnum_day_prod = function () {
            $(".contentdetail").empty();
            $(".show_mode").css("display", "block");
            var jobnum_day_prod_html = `
            <div style="height: 55%; padding-left: 2px; border-right: 2px solid white; background-color: #f3f3f4; ">
                <label>@Html.Raw(Label.Time)：</label>
                <select id="date-dropdown" style="height: 0.3rem; font-size: 0.16rem;"></select>
                <div id="jobnum_hour_chart" style="height: 4.7rem;"></div>
            </div>
            <div style="height: 55%; padding-left: 2px; background-color: #f3f3f4; ">
                <label>@Html.Raw(Label.Process)：</label>
                <select id="process-dropdown" style="height: 0.3rem; font-size: 0.16rem;"></select>
                <div id="process_hour_chart" style="height: 4.7rem;"></div>
            </div>
            <div style="height: 45%; width: 100%; background-color: #f3f3f4;">
                <button id="btn_export" onclick ="jobnum_export();">@Html.Raw(Label.Export+Label.Detail)</button>
                <div id="table_detail" class="detail" style="height: 5rem;">
                    <table id="AssemblyTable" class="DataSheet" border="1" style="color:black;width:100%;height:100%">
                        <thead><tr></tr></thead>
                        <tbody id="detail_tbody"></tbody>
                        <tfoot><tr></tr></tfoot>
                    </table>
                </div>
            </div>`;
            $(".contentdetail").append(jobnum_day_prod_html);
            //date-dropdown
            var days = ProdTab.Tab4.map(item => item.DAY);
            var uniqueDays = [];
            days.forEach(day => {
                if (!uniqueDays.includes(day)) {
                    uniqueDays.push(day);
                }
            });
            uniqueDays.sort((a, b) => new Date(a) - new Date(b));
            uniqueDays = uniqueDays.map(day => new Date(day).toISOString().split('T')[0]);
            $("#process-dropdown").empty();
            uniqueDays.forEach((day, index) => {
                const option = $('<option></option>').val(day).text(day);
                if (index === 0) {
                    option.prop('selected', true);
                }
                $("#date-dropdown").append(option);
            });
            $('#date-dropdown').prop('selectedIndex', 0).trigger('change');

            //数据列表
            data_detail_grid();
        }
        //process-dropdown
        var process_dropdown = function () {
            var process_data = ProdTab.Tab3.filter(function (item) {
                return new Date(item.DAY).toISOString().split('T')[0] == $("#date-dropdown").val(); //$(this).val()
            });
            var process = process_data.map(item => item.PROCESS_ID);
            var uniqueprocess = [];
            process.forEach(itme => {
                if (!uniqueprocess.includes(itme)) {
                    uniqueprocess.push(itme);
                }
            });
            uniqueprocess.sort((a, b) => new Date(a) - new Date(b));
            $("#process-dropdown").empty();
            uniqueprocess.forEach((item, index) => {
                const option = $('<option></option>').val(item).text(item);
                if (index === 0) {
                    option.prop('selected', true);
                }
                $("#process-dropdown").append(option);
            });
        }
        //生成chartoption
        var detail_chart_option = function (id, data) {
            var isjobnum = id.includes("jobnum");
            var isprocess = id.includes("process");
            var date = $("#date-dropdown").val();
            var jobnum = data[0].JOB_NUM;
            var process = $("#process-dropdown").val();
            var charttitle = isjobnum ? `${jobnum}小时产出` : `${process}小时产出`;
            var chartDom = document.getElementById(id);
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            var xAxisData = data.map(function (item) {
                return parseInt(item.HOUR);
            });
            var pass = data.map(function (item) {
                return item ? item.OUTPUT : 0;
            });
            var fail = data.map(function (item) {
                return item ? item.INPUT - item.OUTPUT : 0;
            });
            var yield = data.map(function (item) {
                return parseFloat((item.OUTPUT / item.INPUT) * 100).toFixed(2);
            });
            var InputData = data.map(function (item) {
                return item ? item.INPUT : 0;
            });
            var vaulemax = Math.max.apply(null, InputData);
            var yAxismax = Math.ceil(vaulemax) + (10 - Math.ceil(vaulemax) % 10);
            var myChart = echarts.init(chartDom);
            var options = {
                label: {
                    show: true,
                    color: 'white',
                    fontSize: '0.12rem',
                    fontWeight: 'bold'
                },
                textStyle: {
                    fontSize: '0.1rem'
                },
                title: {
                    text: `${charttitle}`,
                    textStyle: {
                        fontSize: '0.14rem',
                        textAlign: 'center'
                    }
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.12rem',
                        align: 'left'
                    },
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    data: ['PASS', 'FAIL', 'YIELD'],
                    width: '100%',
                    itemGap: 10,
                    itemWidth: 10,
                    itemHeight: 10,
                    textStyle: {
                        fontSize: '0.12rem'
                    }
                },
                grid: {
                    top: '20%',
                    left: '2%',
                    right: '2%',
                    bottom: '5%',
                    containLabel: true
                },
                xAxis:
                {
                    yAxisIndex: 9,
                    type: 'category',
                    data: xAxisData.map(item => item + ":00"),
                    textStyle: {
                        fontSize: '0.12rem'
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: 45,
                        textStyle: {
                            fontSize: '0.12rem'
                        }
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        max: yAxismax * 2 + (yAxismax / 5),
                        interval: Math.ceil((yAxismax * 2 + (yAxismax / 5)) / 6),
                        splitLine: { show: false },
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            interval: 0,
                            textStyle: {
                                fontSize: '0.14rem',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    {
                        type: 'value',
                        min: 0,
                        max: 120,
                        interval: 20,
                        scale: true,//刻度范围一致
                        splitLine: { show: false },
                        axisTick: { //y轴刻度线
                            show: true
                        },
                        axisLine: { //y轴
                            show: true
                        },
                        axisLabel: {
                            interval: 0,
                            formatter: function (value) {
                                return value + '%';
                            },
                            textStyle: {
                                fontSize: '0.14rem',
                                fontWeight: 'bold'
                            }
                        }
                    }
                ],
                series: [
                    {
                        data: fail.map(item => parseInt(item) > 0 ? item : null),
                        name: 'FAIL',
                        type: 'bar',
                        stack: 'stack1',
                        barCategoryGap: '50%',
                        barWidth: '40%',
                        itemStyle: {
                            normal: {
                                color: '#FF3374',
                                shadowColor: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    {
                        data: pass.map(item => parseInt(item) > 0 ? item : null),
                        name: 'PASS',
                        type: 'bar',
                        stack: 'stack1',
                        barCategoryGap: '50%',
                        barWidth: '40%',
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: '#07C160',
                                shadowColor: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    {
                        name: 'YIELD',
                        type: 'line',
                        yAxisIndex: 1,
                        zlevel: 0,
                        data: yield.map(item => parseInt(item) > 0 ? item : 0),
                        lineStyle: { normal: { width: 3 } },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                    offset: 0,
                                    color: 'rgba(237, 178, 23, 0.5)'
                                }, {
                                    offset: 0.8,
                                    color: 'rgba(237, 178, 23, 0.1)'
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                                shadowBlur: 12
                            }
                        },
                        itemStyle: { normal: { color: '#EDB217 ' } },
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                formatter: function (params) { return params.value + '%'; },
                                color: '#E1AB19'
                            }
                        }
                    }
                ]
            };
            myChart.setOption(options);
            window.addEventListener('resize', function () {
                myChart.resize();
            });
        }
        //工单小时产出
        var jobnum_hour_chart = function () {
            var data = ProdTab.Tab4.filter(function (item) {
                return new Date(item.DAY).toISOString().split('T')[0] == $("#date-dropdown").val();
            });
            detail_chart_option("jobnum_hour_chart", data);
        }
        //工序小时产出
        var process_hour_chart = function () {
            var data = ProdTab.Tab3.filter(function (item) {
                return new Date(item.DAY).toISOString().split('T')[0] == $("#date-dropdown").val() && item.PROCESS_ID == $("#process-dropdown").val();
            });
            detail_chart_option("process_hour_chart", data);
        }
        //数据明细
        var data_detail_grid = function () {
            $("#table_detail").css("overflow-y", "auto");
            var data = ProdTab.Tab2;
            var table = $('#AssemblyTable');
            var tbody = table.find('tbody');
            $("#AssemblyTable>thead>tr,#detail_tbody,#AssemblyTable>tfoot>tr").empty();
            // 动态生成表头
            var headerRow = table.find('thead tr');
            var headers = Object.keys(data[0]);
            headers.forEach(function (header) {
                headerRow.append('<th>' + header + '</th>');
            });
            // 生成表格内容
            data.forEach(function (row, index) {
                index++;
                var newRow = $(`<tr class="${(index % 2) > 0 ? "Zebra" : "ZebraTo"}"></tr>`);
                headers.forEach(function (header, columnindex) {
                    if (typeof row[header] === "number") {
                        row[header] = row[header].toFixed(0);
                    }
                    if (header === "TEST_TIME") {
                        row[header] = row[header].replace(/\T/g, '&emsp;');
                    }
                    newRow.append(`<td class="truncate">${row[header]}</td>`);
                });
                tbody.append(newRow);
            });
            // 合计
            var colspan = 5;
            var tfootRow = table.find('tfoot tr');
            tfootRow.append(`<th colspan="${colspan}">合计</th>`);
            var sum_input = data.reduce(function (sum, item) {
                return sum + (item ? (parseInt(item.INPUT_QTY) || 0) : 0);
            }, 0);
            var sum_output = data.reduce(function (sum, item) {
                return sum + (item ? (parseInt(item.OUTPUT_QTY) || 0) : 0);
            }, 0);
            var sum_fail = data.reduce(function (sum, item) {
                return sum + (item ? (parseInt(item.INPUT_QTY - item.OUTPUT_QTY) || 0) : 0);
            }, 0);
            headers.forEach(function (header, columnindex) {
                if (columnindex >= colspan) {
                    //sum_input
                    if (header === "PRODUCTION_LOT_NO") {
                        tfootRow.append(`<th>INPUT：${sum_input}</th>`);
                    }
                    //sum_output
                    if (header === "INPUT_QTY") {
                        tfootRow.append(`<th>OUTPUT：${sum_output}</th>`);
                    }
                    //sum_fail
                    if (header === "OUTPUT_QTY") {
                        tfootRow.append(`<th>FAIL：${sum_fail}</th>`);
                    }
                    //yield
                    if (header === "TEST_TIME") {
                        var yield = parseFloat(sum_input > 0 ? (sum_output / sum_input) * 100 : 0).toFixed(2) + '%';
                        tfootRow.append(`<th>YIELD：${yield}</th>`);
                    }
                }
            });
        }

        $(document).on('change', '#date-dropdown', function () {
            process_dropdown();
            jobnum_hour_chart();
            process_hour_chart();
        });

        $(document).on('change', '#process-dropdown', function () {
            process_hour_chart();
        });

        var jobnum_export = function () {
            exportXlsx(ProdTab.Tab2, `${ProdTab.Tab4[0].JOB_NUM}_DATA`);
        }

    </script>
</body>
</html>
